package test.transferFile3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.handler.stream.StreamIoHandler;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * 文件传输客户端
 * 
 * @author Simple
 * @date 2013-6-24 上午11:56:56
 * @Description TODO
 */
public class FileClient extends StreamIoHandler {

  private IoSession session;

  @Override
  protected void processStreamIo(IoSession session, InputStream in, OutputStream out) {
    // TODO Auto-generated method stub
    File sendFile=new File("e:\\1.txt");
    FileInputStream fis=null;
    try {
      fis=new FileInputStream(sendFile);
    } catch(FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // 客户端一般都用一个线程实现即可，不用线程池，放入线程让其执行
    new IoStreamThreadWork(fis, out).start();
    return;
  }

  public void createClientStream() {
    NioSocketConnector connector=new NioSocketConnector();
    DefaultIoFilterChainBuilder chain=connector.getFilterChain();
    ObjectSerializationCodecFactory factory=new ObjectSerializationCodecFactory();
    factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);
    factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);
    chain.addLast("loger", new LoggingFilter());
    connector.setHandler(new FileClient());
    ConnectFuture cf=connector.connect(new InetSocketAddress("localhost", 9999));
    cf.awaitUninterruptibly();
    IoSession session=cf.getSession();
    setSession(session);
  }

  public void setSession(IoSession session) {
    this.session=session;
  }

  public IoSession getSession() {
    return session;
  }

  public static void main(String[] args) {
    new FileClient().createClientStream();
  }
}
